<?php

namespace App\Models\Home;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Wages extends Model
{
    protected $table = 'wages';
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo('App\Models\Home\Users','assign','id');
    }

    public function getList($between=array(),$skip=0,$limit,$opt=array(),$in=array()){
        $query = self::orderBy('month','desc')->with(['user']);

        if ($between && count($between) == 2){
            $query = $query->whereBetween('updated_at', $between);
        }

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        if (!empty($in) && count($in)==2){
            $query = $query->whereIn($in[0],$in[1]);
        }

        if (isset($limit)){
            $query = $query->skip($skip)->limit($limit);
        }

        $list = $query->get();

        foreach ($list as $k => $v){

            $list[$k]->month = date('Y-m',strtotime($v->month));

            $list[$k]->user_name = $v->user?$v->user->username:'';

            $list[$k]->add_total = intval($v->add_money1)+intval($v->add_money2)+intval($v->add_money3)+intval($v->add_money4)+intval($v->add_money5)+intval($v->add_money6)+intval($v->add_money7)+intval($v->add_money8)+intval($v->add_money9)+intval($v->add_money10)+intval($v->add_money11)+intval($v->add_money12)+intval($v->add_money13)+intval($v->add_money14);

            $list[$k]->cut_total = intval($v->cut_money1)+intval($v->cut_money2)+intval($v->cut_money3)+intval($v->cut_money4)+intval($v->cut_money5)+intval($v->cut_money6)+intval($v->cut_money7)+intval($v->cut_money8)+intval($v->cut_money9);

            $list[$k]->total = intval($list[$k]->kpi_bonus)+intval($list[$k]->kpi_money)+intval($list[$k]->salary)+intval($list[$k]->add_total)-intval($list[$k]->cut_total);

        }

        return $list;

    }

    public function getCount($between=array(), $opt=array(),$in=array()){
        $query = self::orderBy('month','desc');

        if ($between && count($between) == 2){
            $query = $query->whereBetween('updated_at', $between);
        }

        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        if (!empty($in) && count($in)==2){
            $query = $query->whereIn($in[0],$in[1]);
        }

        $count = $query->count();

        return $count;
    }

}
